<?php
namespace app\modules\admin\controllers;

use app\controllers\UploadControllerTrait;
use app\models\Article;
use app\models\ArticleCategory;
use app\models\ManagerLog;
use Yii;
use yii\data\Pagination;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;

/**
 * 资讯管理
 *
 * Class ArticleController
 * @package app\modules\admin\controllers
 */
class ArticleController extends BaseController
{
    /**
     * 资讯管理
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionList()
    {
        if (!$this->manager->can('article/list')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $query = Article::find();
        $query->andFilterWhere(['cid'=>Yii::$app->request->get('search_cid')]);
        $query->andFilterWhere(['like', 'title', Yii::$app->request->get('search_title')]);
        $query->andFilterWhere(['status'=>Yii::$app->request->get('search_status')]);
        $query->andWhere(['status'=>[Article::STATUS_DRAFT, Article::STATUS_WAIT, Article::STATUS_PUBLISHED, Article::STATUS_REFUSED]]);
        $pagination = new Pagination(['totalCount'=>$query->count()]);
        $model_list = $query->orderBy('id DESC')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('list', [
            'model_list'=>$model_list,
            'pagination'=>$pagination
        ]);
    }

    /**
     * 添加/修改资讯
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return string
     */
    public function actionEdit()
    {
        if (!$this->manager->can('article/edit')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $id = Yii::$app->request->get('id');
        if ($id > 0) {
            $model = Article::findOne($id);
            if (empty($model)) {
                throw new NotFoundHttpException('没有找到资讯信息。');
            }
        } else {
            $model = new Article();
            // 管理员添加的资讯uid为NULL
            $model->cid = Yii::$app->request->get('cid');
            $model->add_time = time();
            $model->status = Article::STATUS_WAIT; // 管理员添加的资讯默认状态为待审核
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
            ManagerLog::info($this->manager->id, '', '保存资讯：' . print_r($model->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url'=>Url::to(['/admin/article/list', 'search_cid'=>$model->cid]),
                'txt'=>'资讯列表'
            ]));
        }
        return $this->render('edit', [
            'model'=>$model
        ]);
    }
    
    /**
     * 文件上传AJAX接口
     * @see \app\controllers\UploadControllerTrait
     */
    use UploadControllerTrait;

    /**
     * 删除资讯AJAX接口
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return array
     */
    public function actionDelete()
    {
        if (!$this->manager->can('article/edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = Yii::$app->request->get('id');
        $model = Article::findOne($id);
        if (empty($model)) {
            throw new NotFoundHttpException('没有找到资讯信息。');
        }
        $model->status = Article::STATUS_DELETED;
        $model->save();
        ManagerLog::info($this->manager->id, '', '删除资讯：' . print_r($model->attributes, true));
        return [
            'result'=>'success'
        ];
    }

    /**
     * 资讯分类管理
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionCategory()
    {
        if (!$this->manager->can('article/category')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $query = ArticleCategory::find()->andWhere(['pid'=>NULL]);
        $model_list = $query->orderBy('sort DESC, id ASC')->all();
        return $this->render('category', [
            'model_list'=>$model_list
        ]);
    }


    /**
     * 添加/修改资讯分类
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return String
     */
    public function actionEditCategory()
    {
        if (!$this->manager->can('article/category')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $id = Yii::$app->request->get('id');
        if ($id > 0) {
            $model = ArticleCategory::findOne($id);
            if (empty($model)) {
                throw new NotFoundHttpException('没有找到资讯分类。');
            }
        } else {
            $model = new ArticleCategory();
        }
        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
            ManagerLog::info($this->manager->id, '', '保存资讯分类：' . print_r($model->attributes, true));
            Yii::$app->session->addFlash('success', '数据已保存。');
            Yii::$app->session->setFlash('redirect', json_encode([
                'url'=>Url::to(['/admin/article/category']),
                'txt'=>'资讯分类'
            ]));
        }
        return $this->render('category_edit', [
            'model'=>$model
        ]);
    }

    /**
     * 删除资讯分类AJAX接口
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return array
     */
    public function actionDeleteCategory()
    {
        if (!$this->manager->can('article/category')) {
            throw new ForbiddenHttpException('没有权限');
        }
        $id = Yii::$app->request->get('id');
        $model = ArticleCategory::findOne($id);
        if (empty($model)) {
            throw new NotFoundHttpException('没有找到资讯分类。');
        }
        $model->delete();
        return [
            'result'=>'success'
        ];
    }

    /**
     * 资讯审核
     * @throws ForbiddenHttpException
     * @return string
     */
    public function actionVerify()
    {
        if (!$this->manager->can('article/verify')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $query = Article::find();
        $query->andWhere(['status'=>Article::STATUS_WAIT]);
        $pagination = new Pagination(['totalCount'=>$query->count()]);
        $model_list = $query->orderBy('id DESC')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('verify', [
            'model_list'=>$model_list,
            'pagination'=>$pagination
        ]);
    }

    /**
     * 发布资讯AJAX接口
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @return array
     */
    public function actionPublish()
    {
        if (!$this->manager->can('article/edit')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = Yii::$app->request->get('id');
        $model = Article::findOne($id);
        if (empty($model)) {
            throw new NotFoundHttpException('没有找到资讯信息。');
        }
        $model->status = Article::STATUS_PUBLISHED;
        $model->save();
        ManagerLog::info($this->manager->id, '', '发布资讯：' . print_r($model->attributes, true));
        return [
            'result'=>'success'
        ];
    }

    /**
     * 资讯审核拒绝AJAX接口
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws ServerErrorHttpException
     * @throws BadRequestHttpException
     * @return array
     */
    public function actionRefuse()
    {
        if (!$this->manager->can('article/verify')) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = Yii::$app->request->get('id');
        $remark = Yii::$app->request->get('remark');
        $article = Article::findOne($id);
        if (empty($article)) {
            throw new NotFoundHttpException('没有找到资讯内容。');
        }
        if ($article->status != Article::STATUS_WAIT) {
            throw new ServerErrorHttpException('资讯状态异常。');
        }
        if (empty($remark)) {
            throw new BadRequestHttpException('没有提交拒绝原因。');
        }
        $article->status = Article::STATUS_REFUSED;
        $article->remark = $remark;
        $article->save(false);
        return [
            'result'=>'success'
        ];
    }
}
